package com.test.springboot.springBootUtils.advice;

import java.util.List;

import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.test.springboot.springBootUtils.bean.ResultCode;
import com.test.springboot.springBootUtils.bean.ResultVo;

/**
 * 全局异常处理类
 * @author huyong
 *
 */
@RestControllerAdvice // 这里是用 ControllerAdvice 还是用 @RestControllerAdvice 是有 Controller中接口上的注解决定的
public class ExceptionControllerAdvice {
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public ResultVo<String> MethodArgumentNotVaildExceptionHandler(MethodArgumentNotValidException e) {
		// 从异常对象中获取异常信息并返回给前端
		BindingResult bindingResult = e.getBindingResult();
		List<ObjectError> allErrors = bindingResult.getAllErrors();
		if (!CollectionUtils.isEmpty(allErrors)) {
			ObjectError objectError = allErrors.stream().findFirst().get();
			String defaultMessage = objectError.getDefaultMessage();
			FieldError fieldError = bindingResult.getFieldError();
			String field = fieldError.getField();
			return new ResultVo<String>(ResultCode.VALIDATE_FAILED, field + " is value:" + fieldError.getRejectedValue() + " " + defaultMessage);
		}
		return null;
	}

}
